package org.example.lotterysystem.service.impl;

import org.example.lotterysystem.common.errorcode.ServiceErrorCodeConstants;
import org.example.lotterysystem.common.exception.ServiceExcetion;
import org.example.lotterysystem.common.utils.*;
import org.example.lotterysystem.service.VerificationCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class VerificationCodeServiceImpl implements VerificationCodeService {
    //对于redis里面的key需要标准化：为了区分业务，应该给key定义前缀：
    // VerificationCode_1311111111：1233  User_1311111111：userInfo
    private static final String VERIFICATION_CODE_PREFIX = "VERIFICATION_CODE_";
    private static final Long VERIFICATION_CODE_TIMEOUT = 60L;
    private static final String VERIFICATION_CODE_TEMPLATE_CODE = "123456";


    @Autowired
    private SMSUtil smsUtil;
    @Autowired
    private RedisUtil redisUtil;
    @Override
    public void sendVerificationCode(String phoneNumber) {
        //1、校验手机号
        if(!RegexUtil.checkMobile(phoneNumber)){
            throw new ServiceExcetion(ServiceErrorCodeConstants.PHONE_NUMBER_ERROR);
        }

        //2、生成随机验证码
        String code = CaptchaUtil.getCaptcha(4);
        //3、发送验证码
        //{“code:xxxx”}
        Map<String,String> map = new HashMap<>();
        map.put("code",code);
        smsUtil.sendMessage(VERIFICATION_CODE_TEMPLATE_CODE,phoneNumber, JacksonUtil.writeValueAsString(map));
        //4、缓存验证码
        //一个手机号对应一个验证码
        redisUtil.set(VERIFICATION_CODE_PREFIX+phoneNumber,code,VERIFICATION_CODE_TIMEOUT);
    }

    /**
     * 从redis中获取验证码
     * @param phoneNumber
     * @return
     */
    @Override
    public String getVerificationCode(String phoneNumber) {
        //1、校验手机号
        if(!RegexUtil.checkMobile(phoneNumber)){
            throw new ServiceExcetion(ServiceErrorCodeConstants.PHONE_NUMBER_ERROR);
        }
        return redisUtil.get(VERIFICATION_CODE_PREFIX+phoneNumber);
    }
}
